package com.ltxtiyu.video.tool;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class HttpTool {
	private static final Logger LOGGER = LoggerFactory.getLogger(HttpTool.class);
    private static String encode = "UTF-8";
	 
	@SuppressWarnings("deprecation")
	public static String httpPost(String url, Map<String, String> map){
	        String rs = "";
	        HttpClient httpclient = HttpClients.createDefault();
	        try {
	            HttpPost httpPost = new HttpPost(url);
	            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
	            
	            for(String s : map.keySet()){
	                if(map.get(s) != null){
	                    nvps.add(new BasicNameValuePair(s, map.get(s)));
	                }
	            }
	            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "GBK"));
	            HttpResponse response = httpclient.execute(httpPost);	
	            HttpEntity entity = response.getEntity();
	            
	            if (entity != null) {
	                rs = EntityUtils.toString(entity);
	            }
	        } catch (Exception ex) {
	            ex.printStackTrace();
	        } finally{
	             httpclient.getConnectionManager().shutdown();
	        }
	        System.out.println("rs --- >>>>>>>>>> " + rs);
	        return rs;
	    }
	 
	 /**
		 * 用http模拟form表单提交
		 * @return
		 * @throws IOException
		 */
		public static String httpPostForm(String url, Map<String, Object> params) throws Exception {
			 URL u = null;
		        HttpURLConnection con = null;
		        // 构建请求参数  
		        StringBuffer sb = new StringBuffer();
		        if (params != null) {  
		            for (Entry<String, Object> e : params.entrySet()) {
		                sb.append(e.getKey());  
		                sb.append("=");  
		                sb.append(e.getValue());  
		                sb.append("&");  
		            }  
		            sb.substring(0, sb.length() - 1);  
		        }  
		        System.out.println("send_url:" + url);
		        System.out.println("send_data:" + sb.toString());
			try {  
	            u = new URL(url);
	            con = (HttpURLConnection) u.openConnection();
	            //// POST 只能为大写，严格限制，post会不识别  
	            con.setRequestMethod("POST");  
	            con.setDoOutput(true);  
	            con.setDoInput(true);  
	            con.setUseCaches(false);  
	            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
	            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
	            osw.write(sb.toString());  
	            osw.flush();  
	            osw.close();  
	        } catch (Exception e) {
	            e.printStackTrace();  
	        } finally {  
	            if (con != null) {  
	                con.disconnect();  
	            }  
	        }  
	  
	        // 读取返回内容  
	        StringBuffer buffer = new StringBuffer();
	        try {  
	            //一定要有返回值，否则无法把请求发送给server端。  
	            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
	            String temp;
	            while ((temp = br.readLine()) != null) {  
	                buffer.append(temp);  
	                buffer.append("\n");  
	            }  
	        } catch (Exception e) {
	            e.printStackTrace();  
	        }  
	  
	        return buffer.toString();
		}
		
		/**
		 * 发起https请求并获取结果
		 * 
		 * @param requestUrl
		 *            请求地址
		 * @param requestMethod
		 *            请求方式（GET、POST）
		 * @param outputStr
		 *            提交的数据
		 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
		 */
		public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
			JSONObject jsonObject = null;
			StringBuffer buffer = new StringBuffer();
			try {
				// 创建SSLContext对象，并使用我们指定的信任管理器初始化
				TrustManager[] tm = { new X509TrustManager() {

					public X509Certificate[] getAcceptedIssuers() {
						return null;
					}

					public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

					}

					public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

					}
				} };

				SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
				sslContext.init(null, tm, new java.security.SecureRandom());
				// 从上述SSLContext对象中得到SSLSocketFactory对象
				SSLSocketFactory ssf = sslContext.getSocketFactory();

				URL url = new URL(requestUrl);
				HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
				httpUrlConn.setSSLSocketFactory(ssf);

				httpUrlConn.setDoOutput(true);
				httpUrlConn.setDoInput(true);
				httpUrlConn.setUseCaches(false);
				// 设置请求方式（GET/POST）
				httpUrlConn.setRequestMethod(requestMethod);

				if ("GET".equalsIgnoreCase(requestMethod)) {
					httpUrlConn.connect();
				}
				// 当有数据需要提交时
				if (null != outputStr) {
					OutputStream outputStream = httpUrlConn.getOutputStream();
					// 注意编码格式，防止中文乱码
					outputStream.write(outputStr.getBytes("UTF-8"));
					outputStream.close();
				}

				// 将返回的输入流转换成字符串
				InputStream inputStream = httpUrlConn.getInputStream();
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

				String str = null;
				while ((str = bufferedReader.readLine()) != null) {
					buffer.append(str);
				}
				bufferedReader.close();
				inputStreamReader.close();
				// 释放资源
				inputStream.close();
				inputStream = null;
				httpUrlConn.disconnect();
				jsonObject = JSONObject.parseObject(buffer.toString());
			} catch (Exception e) {
				e.printStackTrace();
				LOGGER.error("发起https请求异常", e);
			}
			return jsonObject;
		}


    /**
     *
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encode);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}"+ ce);
        } catch (Exception e) {
            System.out.println("https请求异常：{}"+ e);
        }
        return null;
    }
		/**
		 * 发送http post请求
		 * 
		 * @param url
		 *            请求url
		 * @param data
		 *            需要提交到微信服务器的json数据
		 * @return 服务端响应的数据
		 */
		public static JSONObject doPost(String url, String data) {
			HttpClient httpClient = null;
			HttpResponse httpResponse = null;
			HttpPost httpPost=null;
			String responseContent="";
			JSONObject resultMap=new JSONObject();
			try {
				LOGGER.info("开始请求接口...");
				httpClient =HttpClients.createDefault();
				httpPost = new HttpPost(url);
				
				LOGGER.info("请求地址："+url);
				
				// 设置http请求头信息
				httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
				// 设置提交的数据的MIME类型和字符编码
				StringEntity entity = new StringEntity(data, ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
				
				LOGGER.info("请求地址："+data);
				
				httpPost.setEntity(entity);
				// 发送http post请求
				httpResponse = httpClient.execute(httpPost);
				// 获取http响应状态码
				int statusCode = httpResponse.getStatusLine().getStatusCode();
				
				LOGGER.info("响应码："+statusCode);
				
				if (statusCode == HttpStatus.SC_OK) {
					// 获取服务器响应的数据并返回
					HttpEntity httpEntity = httpResponse.getEntity();
					responseContent= EntityUtils.toString(httpEntity,"UTF-8");
					LOGGER.info("send success！");
					LOGGER.info("返回结果："+statusCode);
	                resultMap.put("statusCode", statusCode);
	                resultMap.put("response", responseContent);
				}else{
				    LOGGER.info("http response status is " + statusCode);
	           	    resultMap.put("statusCode", statusCode);
	           	    resultMap.put("response", "http response status is " + statusCode);
				}
			}catch(Exception e){
				resultMap.put("statusCode", "500");
	       	    resultMap.put("response", "http response status is " + "500");
				String msg ="访问外部请求的接口失败,发生异常";
				LOGGER.error(msg,e);
				throw new RuntimeException("http接口异常");
			}finally{
				httpPost.releaseConnection();
			}
			return resultMap;
		}
		
		
		/**
		 * 发送http post请求
		 * 
		 * @param url
		 *            请求url
		 *            需要提交到微信服务器的json数据
		 * @return 服务端响应的数据
		 */
		public static String doPostJson(String url) {
			 	HttpClient client = HttpClients.createDefault();
		        HttpPost post = new HttpPost(url);
		        
		        post.setHeader("Content-Type", "application/json");
		        post.addHeader("Authorization", "Basic YWRtaW46");
		        String result = "";
		        
		        try {

		            /*StringEntity s = new StringEntity(json.toString(), "utf-8");
		            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
		                    "application/json"));
		            post.setEntity(s);*/

		            // 发送请求
		            HttpResponse httpResponse = client.execute(post);

		            // 获取响应输入流
		            InputStream inStream = httpResponse.getEntity().getContent();
		            BufferedReader reader = new BufferedReader(new InputStreamReader(
		                    inStream, "utf-8"));
		            StringBuilder strber = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null)
		                strber.append(line + "\n");
		            inStream.close();

		            result = strber.toString();
		            System.out.println(result);
		            
		            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		                
		                    System.out.println("请求服务器成功，做相应处理");
		                
		            } else {
		                
		                System.out.println("请求服务端失败");
		                
		            }
		            

		        } catch (Exception e) {
		            System.out.println("请求异常");
		            throw new RuntimeException(e);
		        }

		        return result;
		}

		/**
		 * 发送http post请求
		 * 
		 * @param url
		 *            请求url
		 *            需要提交到微信服务器的json数据
		 * @return 服务端响应的数据
		 */
		public static String doGet(String url) {
			 	HttpClient client = HttpClients.createDefault();
		        HttpGet get = new HttpGet(url);
		        
//		        post.setHeader("Content-Type", "application/json");
//		        post.addHeader("Authorization", "Basic YWRtaW46");
		        String result = "";
		        
		        try {

		            /*StringEntity s = new StringEntity(json.toString(), "utf-8");
		            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
		                    "application/json"));
		            post.setEntity(s);*/

		            // 发送请求
		            HttpResponse httpResponse = client.execute(get);

		            // 获取响应输入流
		            InputStream inStream = httpResponse.getEntity().getContent();
		            BufferedReader reader = new BufferedReader(new InputStreamReader(
		                    inStream, "utf-8"));
		            StringBuilder strber = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null)
		                strber.append(line + "\n");
		            inStream.close();

		            result = strber.toString();
		            System.out.println(result);
		            
		            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		                    System.out.println("请求服务器成功，做相应处理");
		            } else {
		                System.out.println("请求服务端失败");
		            }
		        } catch (Exception e) {
		            System.out.println("请求异常");
		            throw new RuntimeException(e);
		        }
		        return result;
		}

    /**
     * 发送post请求
     * @param url   请求地址
     * @param params  请求参数Map<String, ? extends Object> params  Object可以为String或者File或者基本类型
     * @throws IOException
     */
    public static String sendPost(String url, Map<String, String> params) throws IOException {
        System.out.println(url);
        String result=null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).build();//.setSocketTimeout(120000)
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            if (params != null && params.size() > 0) {
                for (Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = params.get(key);
                    formparams.add(new BasicNameValuePair(key, value));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formparams, encode));
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity entity = response.getEntity();
                if(entity!=null){
                    result = EntityUtils.toString(response.getEntity(),encode);
                }
                // do something useful with the response body
                // and ensure it is fully consumed
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        return StringUtil.replaceBlank(result);
    }
}
